<%@page import="com.hrms.domain.BlockingStep"%>
<%@page import="org.apache.commons.lang.StringUtils"%>
<%@page import="com.hrms.model.TaskListModel"%>
<%@page import="java.util.Collection"%>
<%@page import="com.google.appengine.api.datastore.KeyFactory"%>
<%@page import="java.util.Map"%>
<%@page import="java.util.Arrays"%>
<%@page import="com.hrms.view.TaskView"%>
<%@page import="org.apache.commons.lang.time.DateUtils"%>
<%@page import="com.hrms.core.Constants"%>
<%@page import="com.hrms.core.Utils"%>
<%@page import="java.util.Date"%>
<%@page import="com.hrms.domain.Task"%>
<%@page import="com.hrms.domain.Employee"%>
<%@page import="com.hrms.domain.BusinessObjectImpl"%>
<%@page import="com.hrms.domain.DailyCell"%>
<%@page import="java.util.List"%>
<%@ taglib prefix="c" tagdir="/WEB-INF/tags" %>
<%
TaskView taskView = request.getAttribute(Task.TYPE) != null ? (TaskView)request.getAttribute(Task.TYPE) : new TaskView();
taskView.service(request, response);
Collection<TaskListModel> model = taskView.getTaskViewModel();
List<Date> viewingDateRange = taskView.getDateRange();
Boolean showDailyCells = taskView.showDailyCell();
Boolean showControls = taskView.isViewable();
%>
<script type="text/javascript">
<!--
function makeRowsForBo(boType, row){
	
	setUserAction(EVENT_NEW);
	//alert(EVENT_NEW);
	var rowNum=0;	
	
	row.insertCell(rowNum++).innerHTML = "#";
	row.insertCell(rowNum++).innerHTML = SELECT_TYPE;
	row.insertCell(rowNum++).appendChild( makeInputElement('idUrl', 10, 10, 'text', '') );
	row.insertCell(rowNum++).appendChild( makeExpandableTextArea('description', 400, 50, 2) );
	<% if(showDailyCells){%>
		row.insertCell(rowNum++).colSpan = 8;
	<%}else{%>
		row.insertCell(rowNum++).appendChild( makeInputElement('date', 10, 10, 'text', '') );
		$("#date").datepicker({ showOn: 'button', buttonImageOnly: true, buttonImage: '/static/images/icon_cal.png' });
	<%} %>
	//row.insertCell(rowNum++).innerHTML = SELECT_STATUS;
	
	row.insertCell(rowNum++).innerHTML = '<a href="javascript:saveItem(<%= Utils.Q %>'+boType+'<%= Utils.Q %>)"><img src="/static/images/buttons/accepted-selected.png" title="save" alt="save" width="20" height="20"></a>';
	
	
	$("textarea#description").autoResize({
	    // On resize:
	    onResize : function() {
	        $(this).css({opacity:0.8});
	    },
	    // After resize:
	    animateCallback : function() {
	        $(this).css({opacity:1});
	    },
	    // Quite slow animation:
	    animateDuration : 300,
	    // More extra space:
	    extraSpace : 40
	});
	//bind validation
	stringFields.push("description");
	stringFields.push("idUrl");
}

var prevValue = '';

function requestCellEdit(cellId, cellDate, taskRef){
	
	if(!inATask){
		
	inATask=true;
	setUserAction(EVENT_EDIT);
	
	var inputVal = $('#'+cellId).html();
	prevValue = inputVal;
	$('#'+cellId).html( makeExpandableTextArea('celldata', 400, 50, 3) );
	
	$("textarea#celldata").val(inputVal);
	$("textarea#celldata").autoResize({
	    // On resize:
	    onResize : function() {
	        $(this).css({opacity:0.8});
	    },
	    // After resize:
	    animateCallback : function() {
	        $(this).css({opacity:1});
	    },
	    // Quite slow animation:
	    animateDuration : 300,
	    // More extra space:
	    extraSpace : 40
	});
	
	$("#<%= TaskView.CELL_DATE %>").val(cellDate);
	$("#<%= TaskView.TASK_KEY %>").val(taskRef);
	
	stringFields.push("celldata");
	
	$('#'+cellId).append( '<br><a href="javascript:saveItem(<%= Utils.Q + Task.TYPE + Utils.Q %>)"><img src="/static/images/buttons/accepted.png" title="save" alt="save" width="20" height="20"></a>');
	$('#'+cellId).append( '<a href="javascript:cancelRequestCellEdit(<%= Utils.Q %>'+cellId+'<%= Utils.Q %>)"><img src="/static/images/buttons/remove-selected.png" title="Cancel" alt="Cancel" width="20" height="20"></a>');
	}
}

function cancelRequestCellEdit(cellId){
	inATask=false;
	setUserAction('');

//	var inputVal = $("textarea#celldata").val();
	 $('#'+cellId).html(prevValue);
	stringFields = new Array();
	
	$("#<%= TaskView.CELL_DATE %>").val('');
	$("#<%= TaskView.TASK_KEY %>").val('');
}

function fetchOnDateRange(dateText){
	saveItem('<%= Task.TYPE %>');
}

function navigateDate(dateTo){
	$("#<%=  TaskView.SELECTED_DATE %>").val(dateTo);
	fetchOnDateRange(dateTo);
}

function fireStatusChangeEvent(workinTaskKey, status){
	//alert(workinTaskKey + status);	
	$("#<%= TaskView.TASK_KEY %>").val(workinTaskKey);
	$("#status").val(status);
	
	if(status == '<%= Constants.Status.Blocking.toString() %>'){
		$( "#<%= BlockingStep.TYPE %>_form" ).dialog("open");		
	}else{
		TaskChangeEvent();
	}
}

function TaskChangeEvent(){
	setUserAction(EVENT_TASK_CHANGE);
	saveItem('<%= Task.TYPE %>');
}


$(function() {
	$( "#<%= BlockingStep.TYPE %>_form" ).dialog({
		autoOpen: false,
		height: 300,
		width: 350,
		modal: true,
		buttons: {
			"Create": function() {
				if(validateNotEmpty($('#BlockingStep_blockingStep').val()) && validateNotEmpty($('#BlockingStep_waitingFor').val())){
					$('#Form<%= Task.TYPE %>').append(
							$('<input/>')
			            .attr('type', 'hidden')
			            .attr('name', 'blockingStep')
			            .val($('#BlockingStep_blockingStep').val()));
					
					$('#Form<%= Task.TYPE %>').append(
							$('<input/>')
			            .attr('type', 'hidden')
			            .attr('name', 'waitingFor')
			            .val($('#BlockingStep_waitingFor').val()));
					
					$( this ).dialog( "close" );				
					TaskChangeEvent();
				}
			}
		}
	});
	
});

var alreadysubmited = false;
function activateBatchEdit(btnObj, boType){
	if( (inATask) && (btnObj.value == "Save") && (!alreadysubmited)){
		alreadysubmited = true;
		setUserAction(EVENT_BATCH_EDIT);
		saveItem('<%= Task.TYPE %>');
	}
	
	if((!inATask) && (!alreadysubmited) ){
		
		inATask=true;
		setUserAction(EVENT_BATCH_EDIT);
		
		
		$('.celldata').each(function (index) {
			var cd = $(this);
			var cellId = cd.attr('id');
			
			var inputVal = $('#'+cellId).html();
			$('#'+cellId).html( makeExpandableTextArea(cellId, 400, 10, 1) );
			
			$("textarea#"+cellId).val(inputVal);
			$("textarea#"+cellId).autoResize({
			    // On resize:
			    onResize : function() {
			        $(this).css({opacity:0.8});
			    },
			    // After resize:
			    animateCallback : function() {
			        $(this).css({opacity:1});
			    },
			    // Quite slow animation:
			    animateDuration : 300,
			    // More extra space:
			    extraSpace : 40
			}).bind('focus', function(){ $(this).trigger('change'); }); //.trigger('change');
			
			
			
		});
		
		btnObj.value = "Save";
	
	}
	
}

//-->
</script>
<div style="width: 100%">
<%@include file="/WEB-INF/include/msg.jsp" %>
<form id="Form<%= Task.TYPE %>" name="Form<%= Task.TYPE %>">
<div align="right" >
<% if(showControls) {%>
<%if(showDailyCells){ %>
	 <input align="right" type="button" value="Edit" class="styledActionButton" onclick="activateBatchEdit(this, '<%= Task.TYPE %>')" title="Batch Edit (Excel View)">
<%} %>
     <input align="right" type="button" value="New" class="styledActionButton" onclick="addNewRow('<%= Task.TYPE %>')" title="Create a new task">
<% } %>     
     <input type="hidden" name="<%= Constants.ACTION %>" id="<%= Constants.ACTION %>" /> 
     <input type="hidden" name="<%= TaskView.CELL_DATE %>"  id="<%= TaskView.CELL_DATE %>">
     <input type="hidden" name="<%= TaskView.TASK_KEY %>"  id="<%= TaskView.TASK_KEY %>">
     <input type="hidden" name="status"  id="status">
</div>    

<div id="<%= BlockingStep.TYPE %>_form" title="Create new Blocking Step">
	<p class="validateTips">All form fields are required.</p>

	<fieldset>
		<label for="BlockingStep_blockingStep">Blocking Step</label>
		<textarea id="BlockingStep_blockingStep"  name="BlockingStep_blockingStep" maxlength="480" ></textarea>
		<br>	
		<label for="BlockingStep_waitingFor">Waiting From</label>
		<input type="text" name="BlockingStep_waitingFor" id="BlockingStep_waitingFor" class="text ui-widget-content ui-corner-all" maxlength="480"/>
	</fieldset>
</div>
<center>
	<table width="100%" cellpadding="0" border="0" cellspacing="0" >
		<tr>
		<td align="left" class="dbfieldLabel ui-widget-header">Progress Items</td>
		<td align="left" class="dbfieldLabel">
			 <input align="right" type="button" value="Prev <%= Utils.escapeHTML("<<") %>" class="styledActionButton" onclick="navigateDate('<%= Utils.formatToSimpleDate( DateUtils.addDays( taskView.getNavigatableDate() , -7) ) %>');" title="Show Previous Week">
		</td>
		<td align="center" class="dbfieldLabel">Date Picker
		 <input type="text" name="<%= TaskView.SELECTED_DATE %>" id="<%=  TaskView.SELECTED_DATE %>" size="10" value="<%= Utils.formatToSimpleDate( taskView.getSelectedDate() ) %>">
			 		<script type="text/javascript">
  					$(document).ready(function(){
    						$("#<%=  TaskView.SELECTED_DATE %>").datepicker({ showOn: 'button', buttonImageOnly: true, buttonImage: '/static/images/icon_cal.png', onSelect: function(dateText, inst){ fetchOnDateRange(dateText) } });
  					});
					</script> 
		</td>
		<td align="right" class="dbfieldLabel">
			 <input align="right" type="button" value="<%= Utils.escapeHTML(">>") %> Next" class="styledActionButton" onclick="navigateDate('<%= Utils.formatToSimpleDate( DateUtils.addDays( taskView.getNavigatableDate() , 7) ) %>');" title="Show Next Week">
		</td>
     	</tr>
 	</table>

<table id="<%= Task.TYPE %>" width="100%" cellpadding="0" border="0" cellspacing="0" class="testgrid">
	<tr class="ui-tabs-nav ui-helper-reset ui-widget-header ui-corner-all"> 
		<c:tableHeader title="#"/>
		<c:tableHeader title="Type"/>
		<c:tableHeader title="BugId"/>
		<c:tableHeader title="Description"/>
		
		<%
	if(showDailyCells){
			for(Date d : viewingDateRange){ %>
		<c:tableHeader title="<%= Utils.formatProgressItemTabDate(d) %>"/>
		<%} 
	}else{%>
		<c:tableHeader title="Planned Date"/>
	<%} %>
		<c:tableHeader title="Current Status"/>
		<c:tableHeader title="Action"/>
	</tr>


<%   if(!model.isEmpty()){ %>
	<%
	Integer no = 0;
	String namer = StringUtils.EMPTY;
	for( TaskListModel  tlm : model ){ 
		Task task = tlm.getTask();	
		no++;
		namer = Task.TYPE +"_"+no;
	%>
	<tr id="<%= namer %>">
	<td class="dbfieldLabel">
			<input type="hidden" name="<%= namer %>_key" value="<%= KeyFactory.keyToString(task.getKey()) %>">
		<div><%= task.getKey().getId() %></div>
	</td>
	<td class="dbfieldLabel"><div id="<%= namer %>_type"><%= Utils.formatString( task.getType() )%></div></td>
	<td class="dbfieldLabel"><div id="<%= namer %>_idUrl"><%= Utils.formatString( task.getIdUrl() ) %></div></td>
	<td class="dbfieldLabel"><div id="<%= namer %>_description"><%= task.getDescription() %></div></td>
	<%
if(showDailyCells){
	Integer count=0;
	for(Date d : viewingDateRange){  count++;
			DailyCell dc  = tlm.getDailyCellByDate(d);	
			String dcNamer = namer + "_"+ DailyCell.TYPE +"_"+count; 
	%>
		<td class="dbfieldLabel" title="Click here to make your inputs." onclick="requestCellEdit('<%= dcNamer %>_celldata', '<%= Utils.formatToSimpleDate(d) %>', '<%= KeyFactory.keyToString(task.getKey()) %>');">
		<input type="hidden" name="<%= dcNamer %>_celldata_date" value="<%= Utils.formatToSimpleDate(d) %>">
		<div id="<%= dcNamer %>_celldata"  class="celldata"><% if(dc != null ){ out.print( dc.getCelldata()); } %></div>
		</td>			
	<%} 
}else{%>
	<td class="dbfieldLabel"><div id="<%= namer %>_date"><%= Utils.formatToSimpleDate( task.getDate() )%></div></td>
<%} %>
	<td class="dbfieldLabel"><div id="<%= namer %>_status"><%= task.getStatus() %></div></td>
	<td>
	<% if(task.getStatus().equals(Constants.Status.Planned.toString())){ %>
		<!-- inprogress -->
		<a href="javascript:fireStatusChangeEvent('<%= KeyFactory.keyToString( task.getKey() ) %>', '<%=Constants.Status.InProgress.toString() %>')"  >
			<img height="12" src="/static/images/task_status/Inprogress.png" title="Make it In Progress"  alt="Make it In Progress"/>
		</a>
		
	<% }else if(task.getStatus().equals(Constants.Status.InProgress.toString())){ %>
		<!-- Blocking or Completed  -->
		<a href="javascript:fireStatusChangeEvent('<%= KeyFactory.keyToString( task.getKey() ) %>', '<%=Constants.Status.Blocking.toString() %>')"  >
			<img height="12" src="/static/images/task_status/blocking.png" title="Make a Blocking Step"  alt="Make a Blocking Step"/>
		</a>
		
			<a href="javascript:fireStatusChangeEvent('<%= KeyFactory.keyToString( task.getKey() ) %>', '<%=Constants.Status.Completed.toString() %>')"  >
			<img height="12" src="/static/images/task_status/completed.gif" title="Completed"  alt="Completed"/>
		</a>
		
	<% }else if(task.getStatus().equals(Constants.Status.Blocking.toString())){ %>
		<!-- inprogress, PROMPT -->
		<a href="javascript:fireStatusChangeEvent('<%= KeyFactory.keyToString( task.getKey() ) %>', '<%=Constants.Status.InProgress.toString() %>')"  >
			<img height="12" src="/static/images/task_status/Inprogress.png" title="Mark it Back to Inprogress"  alt="Mark it Back to Inprogress"/>
		</a>
		
	<% }else if(task.getStatus().equals(Constants.Status.Completed.toString())){ %>
		<!--  resume to Inprogress -->
		<a href="javascript:fireStatusChangeEvent('<%= KeyFactory.keyToString( task.getKey() ) %>', '<%=Constants.Status.InProgress.toString() %>')"  >
			<img height="12" src="/static/images/task_status/Inprogress.png" title="Re Open"  alt="ReOpen"/>
		</a>
	<% } %>
	
	<% if( (task.getType().equals(Constants.TASK_TYPE.BUG.toString())) || (task.getType().equals(Constants.TASK_TYPE.ENH.toString())) ){ %>
		<a href="https://jira.tradecard.com/browse/<%= Utils.formatAndtrimString(task.getType())+"-"+ Utils.formatAndtrimString(task.getIdUrl()) %>">
			<img height="12" src="/static/images/task_status/link.png" title="Jira Reference Url"  alt="Jira Reference Url"/>
		</a>
	<% } %>
	 </td>
	</tr>
<%} }else{%>
 	<c:noResults colspan="11"></c:noResults>
<% } %>
</table>
</center>
<script type="text/javascript">
<!--
$('textarea#BlockingStep_blockingStep').autoResize({
    // On resize:
    onResize : function() {
        $(this).css({opacity:0.8});
    },
    // After resize:
    animateCallback : function() {
        $(this).css({opacity:1});
    },
    // Quite slow animation:
    animateDuration : 300,
    // More extra space:
    extraSpace : 40
});
-->
</script>
</form>
</div>